<?php
/**
 * Created by PhpStorm.
 * User: chenxiaogang
 * Date: 2017/11/30
 * Time: 19:55
 */

namespace User\Controller;


use Common\Controller\AdminbaseController;
use User\Model\RoleUser;

/**
 * Class PadtrialController
 * @package     User\Controller
 * @description 垫审
 * @end
 */
class PadtrialController extends AdminbaseController
{
    /**
     * @var object 订单模型对象
     */
    private $orderModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->orderModel = new \User\Model\Orders();
    }

    /**
     * @use          [垫审列表]
     * @author       chenxiaogang
     */
    public function index()
    {
        $where[] = 'a.renew = 0';
        $where = $this->getIndexWhere($where);
        $count = $this->orderModel->padtral_list_count($where);
        $page = $this->page($count,20);
        $limit = $page->firstRow . ',' . $page->listRows;
        $list = $this->orderModel->padtral_list($where,$limit);
        //取合计
        if(!empty($list)){
            $total = $this->orderModel->padtral_list_total($where);
            $this->assign($total);
        }
        //将负责专员id取出来
        $adminIds = array_column($list,'byusers');
        $admins = [];
        if(!empty($adminIds)){
            $admins = M('Users')->where(['user_status'=>1,'id'=>['in',$adminIds]])->getField('id,user_login',true);
        }
        //将code取出来
        $codes = array_filter(array_column($list,'code'));
        if(!empty($codes)){
            $codes = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( ['code'=>['in',$codes]] )->getField( 'code,name' ,true);
            $this->assign( 'codes', $codes );
        }
        $this->assign('admins',$admins);
        $this->assign('list',$list);
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }

    /**
     * @use          [得到垫审列表的查询条件]
     * @author       chenxiaogang
     * @return array
     */
    private function getIndexWhere($where = [])
    {
        $byuser = I( 'request.byusers');
        if($byuser === 2){//看到未认领的
            $where[] = 'byusers=0';
        }elseif($byuser === 0 || $byuser === 3){//默认（或者指定只能看自己的）只能看自己的
            $where[] = 'byusers='.get_current_admin_id();
        }
        if($name = I( 'request.name' )) {
            $where[] = 'b.name like "%' . $name . '%"';
        }
        if($mobile = I('request.mobile')){
            $where[] = 'mobile like "%'.$mobile.'%"';
        }
        if($starts = I('request.starts')){
            $where[] = 'a.crtime >= "' . $starts.' 00:00:00' . '"';
        }
        if($ends = I('request.ends')){
            $where[] = 'a.crtime <= "' . $ends.' 23:59:59' . '"';
        }
        //快速审核
        $fast_auditing = I( 'request.fast_auditing', 0 );
        if(!empty( $fast_auditing ) && is_numeric($fast_auditing)) {
            $fast_auditing-=1;
            $where[] = 'a.fast_auditing =' . $fast_auditing ;
        }
        //必须条件
        $where[] = 'a.status=10';
        $where[] = 'a.overdue_m_status IS NULL';
        $whereStr = implode(' AND ',$where);
        return $whereStr;
    }

    /**
     * @use          [垫审操作]
     * @author       chenxiaogang
     */
    public function padtrial()
    {
        $p_param = I( 'post.options' );
        //$g_param = $_GET;
        $orderId = $p_param['id'];
        $is_pass = $p_param['is_pass'];//0审核不通过 1审核通过
        //直接认领该客户（贷后认领）
        $user_id = $this->orderModel->where(['id'=>$orderId])->getField('user_id');
//        if(!empty($user_id)){
//            M('user','system_',C('DB_CONFIG2'))->where(['id'=>$user_id])->save(['byusers_loan_m1'=>get_current_admin_id()]);
//        }
        $system_amount_id = $p_param['amount'];
        $system_amount = M('amount','system_',C('DB_CONFIG2'))->find($system_amount_id);
        if(empty($system_amount)){
            $this->error('没有这个额度');
        }
        $loan_day = 0;
        switch((int)$p_param['loan_day']){
            case 1:
                $loan_day = 7;
                break;
            case 2:
                $loan_day = 14;
                break;
            case 3:
                $loan_day = 21;
                break;
            case 4:
                $loan_day = 28;
                break;
            default:
                $this->error('没有这个天数');
                break;
        }
        //更改额度配置
        $this->orderModel->where('id='.$orderId)->save([
            'amount'=>$system_amount['amount'],
            'loan_amount'=>$system_amount['amount'],
            'interest'=>$system_amount['interest'],
            'examine'=>$system_amount['examine'],
            'consulting'=>$system_amount['consulting'],
            'stages'=>$p_param['stages'],
            'loan_day'=>$loan_day,
            'modtime' => date( 'Y-m-d H:i:s' ),
        ]);

        if($is_pass){
            $this->orderModel->where('id='.$orderId)->save(['overdue_m_status'=>0,'status'=>10]);
        }else{
            $sql = "UPDATE orders SET `status`=6 , `overdue_m_status`=0 WHERE id=".$orderId." AND `status`=10";//将订单改成不通过
            $this->orderModel->execute($sql);
            //将用户改一下type_borr，从2变成1
            M('user','system_',C('DB_CONFIG2'))->where(['id'=>$user_id,'type_borr'=>2])->save(['type_borr'=>1]);
        }
        //添加system_log
        set_log( $p_param['id'], 1, $is_pass, $p_param['messgae'] );
        $url = $this->jum_url . "?app_act=index/wechat_r_f";
        $post_data = [
            'id' => $p_param['user_id'],
            'amount' => $p_param['is_pass'],
            'type' => 1,
            'sign' => md5( '消息提醒' . md5( 'nuonuojinfu321' ) . $p_param['user_id'] ),
        ];
        A( 'indexlinks' )->http_post( $url, $post_data );
        $this->success( "审核成功！", !empty($p_param['from_url'])?htmlspecialchars_decode($p_param['from_url']):U( "Padtrial/index") );
    }

    /**
     * 续借垫审列表
     */
    public function renew_padtrial(){
        $where[] = 'a.renew = 1';
        $where = $this->getIndexWhere($where);
        $count = $this->orderModel->padtral_list_count($where);
        $page = $this->page($count,20);
        $limit = $page->firstRow . ',' . $page->listRows;
        $list = $this->orderModel->padtral_list($where,$limit);
        //取合计
        if(!empty($list)){
            $total = $this->orderModel->padtral_list_total($where);
            $this->assign($total);
        }
        //将负责专员id取出来
        $adminIds = array_column($list,'byusers');
        $admins = [];
        if(!empty($adminIds)){
            $admins = M('Users')->where(['user_status'=>1,'id'=>['in',$adminIds]])->getField('id,user_login',true);
        }
        //将code取出来
        $codes = array_filter(array_column($list,'code'));
        if(!empty($codes)){
            $codes = M( "distribution", 'system_', C( 'DB_CONFIG2' ) )->where( ['code'=>['in',$codes]] )->getField( 'code,name' ,true);
            $this->assign( 'codes', $codes );
        }
        $this->assign('admins',$admins);
        $this->assign('list',$list);
        $this->assign( "page", $page->show( 'Admin' ) );
        $this->display();
    }



}